const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const passport = require('passport');

const Blogs = require('../../models/Blogs');
const Catagory = require('../../models/Catagory');

router.get('/', (req,res)=>{
	res.json([
		{
			title:'blogs列表',
			api:'api/blogs/list',
			post:'get',
			params:{
				page:'第几页',
				pageSize:'一页显示几条数据',
				title:'标题(模糊查询)',
				catagory:'catagory 的id',
				country:'country 的id',
				city:'city 的id',
				authour:'authour 的id',
				status:'状态'
			}
		},
		{
			title:'blogs新增',
			api:'api/blogs/add',
			post:'post',
			params:{
				status:'状态,必填 ； 1：draft, 2：review, 3：comment 和 4：publish.',
				blogPic:'封面图片',
				title:'标题,必填',
				relatedBlogs:'数组，最大支持3个, 格式[{id:2,name:2222,...},....]',
				conent:'文章内容,必填',
				country:'{id:1,name:q111,...},必填',
				city:'{id:1,name:q111,...},必填',
				authour:'{id:1,name:q111,...}',
				catagory:'{id:1,name:q111,...},必填',
				location:'{id:1,name:q111,...},必填',
				blogLanguage:'文章语言,必填'
			},
			Header: '头部验证 Header：{Authorization:token字段}'
		},{
			title:'blogs删除',
			api:'api/blogs/delete/:id',
			post:'delete',
			params:{
				id:'文章id',
			},
			Header: '头部验证 Header：{Authorization:token字段}'
		},{
			title:'blogs编辑',
			api:'api/blogs/edit/:id',
			post:'put',
			params:{
				status:'状态,必填',
				blogPic:'封面图片',
				title:'标题,必填',
				relatedBlogs:'数组，最大支持3个, 格式[{id:2,name:2222,...},....]',
				conent:'文章内容,必填',
				country:'{id:1,name:q111,...},必填',
				city:'{id:1,name:q111,...},必填',
				authour:'{id:1,name:q111,...}',
				catagory:'{id:1,name:q111,...},必填',
				location:'{id:1,name:q111,...},必填',
				blogLanguage:'文章语言,必填'
			},
			Header: '头部验证 Header：{Authorization:token字段}'
		},{
			title:'blogs详情',
			api:'api/blogs/:id',
			post:'get',
		},
	])
})
router.post('/add', passport.authenticate('jwt',{session:false}), (req, res)=>{
	let params={}
	if (req.body.title) params.title = req.body.title
	if (req.body.status) {
		switch (req.body.status) {
			case 1:
			case 2:
			case 3:
			case 4:
				params.status = Number(req.body.status)
			default:
				return res.status(400).json({
					msg:"status 必须Number且是 1, 2,3,4",
					status:0
				})
		}

	}
	if (req.body.relatedBlogs) params.relatedBlogs = req.body.relatedBlogs
	if (req.body.conent) params.conent = req.body.conent
	if (req.body.blogLanguage) params.blogLanguage = req.body.blogLanguage
	if (req.body.country && req.body.country.id && req.body.country.name) {
		params.country = req.body.country
	} else {
		return res.status(400).json({
			msg:"country 是对象，格式{id:'',name:''}",
			status:0
		})
	}
	if (req.body.city && req.body.city.id && req.body.city.name) {
		params.city = req.body.city
	} else {
		return res.status(400).json({
			msg:"city 是对象，格式{id:'',name:'',...}",
			status:0
		})
	}
	if (req.body.authour && req.body.authour.id && req.body.authour.name) {
		params.authour = req.body.authour
	} else {
		return res.status(400).json({
			msg:"authour 是对象，格式{id:'',name:'',...}",
			status:0
		})
	}
	if (req.body.catagory && req.body.catagory.id && req.body.catagory.name) {
		params.catagory = req.body.catagory
	} else {
		return res.status(400).json({
			msg:"catagory 是对象，格式{id:'',name:'',....}",
			status:0
		})
	}
	if (req.body.location && req.body.location.id && req.body.location.name) {
		params.location = req.body.location
	} else {
		return res.status(400).json({
			msg:"location 是对象，格式{id:'',name:''，...}",
			status:0
		})
	}
	if (req.body.relatedBlogs && req.body.relatedBlogs.length>3){
		return res.status(400).json({
			msg:'relatedBlogs 最大支持3个',
			status:0
		})
	}

	new Blogs(params).save().then(data=>{
		Catagory.findOne({_id:params.catagory.id}).then(catagory => {
			let catagoryParams = {
				blog_num: catagory.blog_num+1,
				update_time:Date.now()
			}
			Catagory.findOneAndUpdate(
				{_id:params.catagory.id},
				{$set:catagoryParams},
				{new:true}
			).then(data => {
			})
		})
		res.json({
			data,
			status:2
		})
	}).catch(err=>res.status(400).json({
		msg:err,
		status:0
	}))


})

router.get('/list', (req, res) => {
	let count =0;
	let query = {};
	if (req.query.title) query.title = {$regex:req.query.title};
	if (req.query.catagory) query['catagory.id'] = req.query.catagory;
	if (req.query.country) query['country.id'] = req.query.country;
	if (req.query.city) query['city.id'] = req.query.city;
	if (req.query.authour) query['authour.id'] = req.query.authour;
	if (req.query.status) query.status = req.query.status;
	let page = parseInt(req.query.page) || 1;
	let rows = req.query.pageSize || 10;
	let skip=0;
	let limit = 0;
	if(page <= 1){
		skip =0;
	} else {
		skip = rows*page - rows
	}
	Blogs.find(query).then(all=>{
		count = all.length
	}).then(() => {
		//总页数 大于当前页数
		if(Math.ceil(count/rows) >= page){
			if(Math.ceil(count/rows) == page){
				limit = count
			} else {
			limit = parseInt(rows)
		}
		} else {
			return res.json({
				data:[],
				status:1,
				msg:'没有数据'
			});
		}
		Blogs.find(query).skip(skip).limit(limit).sort({date:-1}).then(pageData => {
				if (!pageData){
					return res.json({
						data:[],
						count:0,
						page:page,
						status:1,
					})
				}
				res.json({
					data:pageData,
					count,
					page:page,
					status:2,
				})
		}).catch(err=>console.log(err))
	}).catch(err=>console.log(err))
});


router.delete('/delete/:id',passport.authenticate('jwt',{session:false}),(req, res) =>{
	Blogs.findOneAndRemove({_id:req.params.id}).then(profile=>{
		Catagory.findOne({_id:profile.catagory.id}).then(catagory => {
			let catagoryParams = {
				blog_num: catagory.blog_num - 1 > 0 ? catagory.blog_num - 1 : 0,
				update_time:Date.now()
			}
			Catagory.findOneAndUpdate(
				{_id:catagory._id},
				{$set:catagoryParams},
				{new:true}
			).then(data => {
			})
		})

		return res.json({
			status:2,
			msg:'删除成功'
		})
	}).catch(err=>res.status(404).json({msg:'删除失败',status:0}))
})

router.put('/edit/:id',passport.authenticate('jwt',{session:false}),(req, res) => {
	let params={}
	if (req.body.title) params.title = req.body.title
	if (req.body.status) params.status = req.body.status
	if (req.body.relatedBlogs) params.relatedBlogs = req.body.relatedBlogs
	if (req.body.conent) params.conent = req.body.conent
	if (req.body.blogLanguage) params.blogLanguage = req.body.blogLanguage
	if (req.body.country && req.body.country.id && req.body.country.name) {
		params.country = req.body.country
	} else {
		return res.status(400).json({
			msg:"country 是对象，格式{id:'',name:''}",
			status:0
		})
	}
	if (req.body.city && req.body.city.id && req.body.city.name) {
		params.city = req.body.city
	} else {
		return res.status(400).json({
			msg:"city 是对象，格式{id:'',name:'',...}",
			status:0
		})
	}
	if (req.body.authour && req.body.authour.id && req.body.authour.name) {
		params.authour = req.body.authour
	} else {
		return res.status(400).json({
			msg:"authour 是对象，格式{id:'',name:'',...}",
			status:0
		})
	}
	if (req.body.catagory && req.body.catagory.id && req.body.catagory.name) {
		params.catagory = req.body.catagory
	} else {
		return res.status(400).json({
			msg:"catagory 是对象，格式{id:'',name:'',....}",
			status:0
		})
	}
	if (req.body.location && req.body.location.id && req.body.location.name) {
		params.location = req.body.location
	} else {
		return res.status(400).json({
			msg:"location 是对象，格式{id:'',name:''，...}",
			status:0
		})
	}
	if (req.body.relatedBlogs && req.body.relatedBlogs.length>3){
		return res.status(400).json({
			msg:'relatedBlogs 最大支持3个',
			status:0
		})
	}

	// 判断编辑的blog改变了文章的数据id 需要修改文章数据对应的数量
	let BlogsBeforData = {}
	Blogs.findOne({_id:req.params.id}).then(beforData => {
		BlogsBeforData ={
			catagoryId: beforData.catagory.id,
			like_num: beforData.like_num,
			view_num:beforData.view_num
		}
	}).then(() => {
		Blogs.findOneAndUpdate(
			{_id:req.params.id},
			{$set:params},
			{new:true}
		).then(profile => {
			if(!(BlogsBeforData.catagoryId === req.body.catagory.id)){
				Catagory.findOne({_id:BlogsBeforData.catagoryId}).then(befor => {
					let catagoryBefor = {
						blog_num: befor.blog_num - 1 > 0 ? befor.blog_num - 1 : 0,
						like:befor.like - BlogsBeforData.like_num > 0 ? befor.like - BlogsBeforData.like_num : 0,
						view:befor.view - BlogsBeforData.view_num > 0 ? befor.view - BlogsBeforData.view_num : 0,
						update_time:Date.now()
					}
					Catagory.findOneAndUpdate(
						{_id:BlogsBeforData.catagoryId},
						{$set:catagoryBefor},
						{new:true}
					).then(data => {
						Catagory.findOne({_id:req.body.catagory.id}).then(after => {
							let catagoryAfter = {
								blog_num: after.blog_num +1,
								like:after.like + BlogsBeforData.like_num,
								view:after.view + BlogsBeforData.view_num,
								update_time:Date.now()
							}
							Catagory.findOneAndUpdate(
								{_id:req.body.catagory.id},
								{$set:catagoryAfter},
								{new:true}
							).then(data => {

							})
						})
					})
				})
			}
			res.json({
				data:profile,
				status:2
			})
		}).catch(err=>res.status(404).json({
			msg:err,
			status:0
		}))
	})
})

router.get('/:id',(req,res)=>{
	Blogs.findOne({_id:req.params.id}).then(profile=>{
		if(!profile){
			return res.json({
				msg:'没有内容',
				status:1
			});
		} else {
			const catagoryId = profile.catagory.id;
			Catagory.findOne({_id:catagoryId}).then(catagory => {
				let catagoryParams = {
					view:catagory.view + 1,
					update_time:Date.now()
				};
				Catagory.findOneAndUpdate(
					{_id:catagoryId},
					{$set:catagoryParams},
					{new:true}
				).then(data => {
					let updataBlogMum = {
						view_num:profile.view_num+1
					};
					Blogs.findOneAndUpdate(
						{_id:req.params.id},
						{$set:updataBlogMum},
						{new:true}
					).then(data => {
					});
				})
			});

			res.json({
				data:profile,
				status:2
			})
		}

	}).catch(err => res.status(404).json({
		msg:'获取失败',
		status:0
	}))
});


module.exports = router;
